<template>
  <div class="table-box">
    <div class="table-header">
      <el-form
        label-width="80px"
        :inline="true"
        :model="dataList"
        class="form-inline"
      >
        <el-form-item
          class="table-form-item"
          label="机车号"
        >
          <el-input
            :readonly="true"
            v-model="dataList.encode5"
            size="mini"
          />
        </el-form-item>
        <el-form-item
          class="table-form-item"
          label="司机号"
        >
          <el-input
            :readonly="true"
            v-model="dataList.encode11"
            size="mini"
          />
        </el-form-item>
        <el-form-item
          class="table-form-item"
          label="司机"
        >
          <el-input
            :readonly="true"
            v-model="dataList.encode_sj"
            size="mini"
          />
        </el-form-item>
        <el-form-item
          class="table-form-item"
          label="副司机"
        >
          <el-input
            :readonly="true"
            v-model="dataList.encode_fsj"
            size="mini"
          />
        </el-form-item>
        <el-form-item
          class="table-form-item"
          label="文件数"
        >
          <el-input
            :readonly="true"
            v-model="dataList.fileNum"
            size="mini"
          />
        </el-form-item>
        <el-form-item
          class="table-form-item"
          label="总容量"
        >
          <el-input
            :readonly="true"
            :value="`${totalSize.toFixed(4)}Mb`"
            size="mini"
          />
        </el-form-item>
        <el-form-item
          class="table-form-item"
          label="日期"
        >
          <el-input
            :readonly="true"
            v-model="dataList.encode4"
            size="mini"
          />
        </el-form-item>
        <el-form-item
          class="table-form-item"
          style="width: 90%;"
          label="文件路径"
        >
          <el-input
            :readonly="true"
            v-model="dataList.filePath"
            size="mini"
          />
        </el-form-item>
      </el-form>
    </div>
    <div class="table-content">
      <div style="padding-bottom: 10px; display: flex; align-items: center; ">
        <el-button
          size="mini"
          type="primary"
          @click="download"
          :disabled="batchFile.loading"
          :icon="batchFile.loading ? 'el-icon-loading' : 'el-icon-download'"
        >
          {{ batchFile.loading ? '下载中....' : '下载' }}
        </el-button>
        <div />
      </div>
      <el-table
        :data="list"
        border
        height="380px"
        size="mini"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column
          label="通道"
          prop="channelNum"
          show-overflow-tooltip
          width="80"
        />
        <el-table-column
          label="起止时间"
          prop="fileTime"
          show-overflow-tooltip
        />
        <el-table-column
          label="容量(Mb)"
          prop="size"
          show-overflow-tooltip
          width="80"
        />
        <el-table-column
          label="文件名"
          prop="url"
          show-overflow-tooltip
        />
      </el-table>
    </div>
  </div>
</template>

<script>
// import { BatchFile } from '@/facade/download'
import JSZip from "jszip";
import FileSaver from "file-saver";
import axios from 'axios'
export default {
  data(){
    return{
      baseUrl: '',
      selectionList: [],
      // batchFile: new BatchFile(),
      batchFile: {
        loading: false
      },
      list: [],
      dataList: {},
      zip:new JSZip(),
      baseURL: ''
    }
  },
  props:{
    form: {
      type: Object,
      default: {}
    }
  },
  computed: {
    totalSize:{
      get(){
        const size = this.list.reduce((result, video) => result + video.size, 0)
        return size
      }
    },
    files:{
      get(){
        const num = this.list.length
        return num
      }
    }
  },
  mounted() {
    this.getBaseUrl()
  },
  created() {
    this.id = this.$route.query.id?this.$route.query.id:''
    this.recordId = this.$route.query.recordId?this.$route.query.recordId:''
    this.getTable()
    this.dataList = this.form
    console.log('from***',this.form)
  },
  methods: {
    getBaseUrl(){
      axios.get('/api/index/quest_url').then(res => {
        this.baseURL = res.data.data
      })
    },
    getTable(){
      axios.get(`/api/ApiData/index?url=api/idx/mp4/getMp4ByRecordId&method=GET&id=${this.id}&recordId=${this.recordId}`).then(res => {
          res.data.data.forEach(item => {
          item.fileTime = item.prefixDate + ' '+ this.getSeconds(item.suffixDate)
        })
          this.list = res.data.data
        })
    },
    getSeconds(value){
      if(value){
        let arr = Array.from(value);
        arr = arr.map((item,index) => {
          if(index == 1){
            item = item + ':'
          }
          if(index == 3){
            item = item + ':'
          }
          return item
        })
        return arr.join('')
      }
    },
    download(blob, fileType) {
      if (this.selectionList.length <= 0) {
        this.$message.warning('请选择要下载的视频！')
        return false
      }
      let arr = []
      console.log('985',this.selectionList.length)
      if(this.selectionList.length<=1){
        this.selectionList.forEach((item,index) => {
          if(this.selectionList.length==1){
            arr.push(`filePathList=${this.form.filePath}${item.url}.mp4`)
          }
        })
      } else {
        this.selectionList.forEach((item,index) => {
           arr.push(`filePathList=${this.form.filePath}${item.url}.mp4&`)
        })
      }
      const url = `${this.baseURL}api/idx/index/downloadFile?${arr}`
      this.downFile(url)
    },
    downFile(url){
      const elemIF = document.createElement('a')
      elemIF.href = url
      elemIF.style.display = 'none'
      elemIF.click()
    },
    // 下载全部附件   downloadBtn<下载全部附件>按钮绑定事件
    // download() {
    //   if (this.selectionList.length <= 0) {
    //     this.$message.warning('请选择要下载的视频！')
    //     return false
    //   }
    //   console.log('selectionList',this.selectionList)
    //   var blogTitle = `全部附件`; // 下载后压缩包的名称
    //   var zip = new JSZip();
    //   var promises = [];
    //   let cache = {};
    //   for (let item of this.selectionList) {
    //     console.log('item.videoUrl',item.videoUrl)
    //     item.videoUrl = 'http://test1.dounong001.com/api/idx/video/getVideo/HXD3C0288_成都运达_01_一端路况_20200617_115524.mp4'
    //     // item.videoUrl为文件链接地址
    //     // item.fileName为文件名称
    //     if(item.videoUrl) {
    //       const promise = this.getImgArrayBuffer(item.videoUrl).then((data) => {
    //         console.log('123',data)
    //         // 下载文件, 并存成ArrayBuffer对象(blob)
    //         zip.file(item.url, data, { binary: true }); // 逐个添加文件
    //         cache[item.url] = data;
    //       });
    //       console.log('promise',promise)
    //       // promises.push(promise);
    //     } else {
    //     // feilePath地址不存在时提示
    //       alert(`附件${item.videoUrl}地址错误，下载失败`);
    //     }
    //   }
    //   Promise.all(promises).then(() => {
    //     zip.generateAsync({ type: "blob" }).then((content) => {
    //       // 生成二进制流
    //       FileSaver.saveAs(content, blogTitle); // 利用file-saver保存文件  blogTitle:自定义文件名
    //     }).catch((res) => {
    //       console.log('33',res)
    //     });
    //   }).catch((res) => {
    //     alert("文件压缩失败");
    //   });
    // },
      // 1. 定义回调函数
      handleResponse(data) {
          console.log(data); // 处理数据
      },
     //文件以流的形式获取（参数url为文件链接地址）
      getImgArrayBuffer(url) {
        return new Promise((resolve, reject) => {
          //通过请求获取文件blob格式
          let xmlhttp = new XMLHttpRequest();
          xmlhttp.open("GET", url, true);
          xmlhttp.responseType = "blob";
          xmlhttp.onreadystatechange = function (res) {
            console.log('xmlhttp',res,xmlhttp)
            if (xmlhttp.status == 200) {
              resolve(xmlhttp.response);
            } else {
              reject(xmlhttp.response);
            }
          };
          xmlhttp.send();
        });
      },
    handleSelectionChange(val) {
      this.selectionList = val
    },
  }
}
</script>

<style scoped>
.table-box::-webkit-scrollbar {
  display: none;
}
.table-box {
  height: 100%;
  overflow: scroll;
}
  .table-content {
    height: calc(100% - 130px);
  }
 .table-box .table-header {
    height: 130px;
    overflow-y: scroll;
  }
  .table-box .table-header  .table-form-item {
    margin-bottom: 5px;
    margin-right: 0;
  }
  /deep/.el-form-item__content {
    width: calc(100% - 80px);
  }
</style>
